package day8.bank;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
public class Taker extends Thread{
    private final Account ac;

    public Taker(String name, Account ac){
        super(name);
        this.ac=ac;
    }
    @Override
    public void run() {
        Random r=new Random();
        while (true){
            int m=r.nextInt(200)+1;
            System.out.println(super.getName()+"打算取钱:"+m+"元，当前余额"+ac.getMoney());
            synchronized (ac){
                try {
                    super.sleep(r.nextInt(60));
                    while (ac.getMoney() < m) {
                        ac.wait();
                        //
                    }
                    System.out.println(super.getName()+"打算取钱:"+m+"元,被唤醒");
                    ac.withDraw(m);
                    System.out.println(super.getName()+"取钱"+m+"元成功，当前余额"+ac.getMoney());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
//    @Override
//    public void run() {
//        Random r=new Random();
//        while (ac.getMoney()>0){
//            int m=r.nextInt(200)+1;
//            System.out.println(super.getName()+"打算取钱:"+m+"元，当前余额"+ac.getMoney());
//            synchronized (ac){
//                if(ac.getMoney()>=m){//不可能把余额变成负值
//                    try {
//                        sleep(r.nextInt(60));
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    ac.withDraw(m);
//                    System.out.println(super.getName()+"取钱"+m+"元成功，当前余额"+ac.getMoney());
//                }else{
//                    System.out.println(super.getName()+"取钱"+m+"元失败，余额不足了");
//                }
//            }
//
//        }
//    }
}
